Selecting a <div> Containing an Image Using :has() in CSS
The :has() pseudo-class in CSS allows you to select elements that contain specific descendants. You can use it to target a <div> that contains an <img> element and apply custom styles.
:has() selects elements based on their descendants or children.
You can combine :has() with other selectors for more precise targeting.
This pseudo-class is particularly useful for styling parent elements depending on their child elements.
In this example, only the <div> that contains an <img> element receives the border and background styles, while other <div> elements remain unchanged.
Use :has() to style containers based on their child elements dynamically.
Check browser compatibility, as older browsers may not fully support :has().
Combine with transitions for smooth visual effects when elements change state.
Avoid overusing :has() for performance-critical layouts, as it may increase rendering complexity.
How would you write a CSS rule to style a div only if it contains an img element inside it?
What happens if you try to use :has() to select a div that contains an image with class 'avatar'?
Our card component sometimes doesn't get the highlighted border even when it has an image — we're using :has() but it's not working in older browsers. How would you debug and fix this?
A designer wants all product cards with images to have a shadow, but we're seeing inconsistent behavior on mobile. How would you investigate whether :has() is the right tool here?
We're using :has() to conditionally style containers with media elements, but performance is degrading on pages with 200+ cards. How would you optimize this without resorting to JS?
The design system uses :has() to apply hover effects to containers with buttons, but it breaks when buttons are conditionally rendered via React. How do you reconcile dynamic content with static CSS selectors?
We're migrating from a legacy JS-based component system to pure CSS-driven styling using :has(), but we still support IE11 in enterprise contracts. How would you architect a migration strategy that balances modern CSS with legacy constraints?
Our CSS-in-JS library doesn't support :has() in SSR. How would you design a cross-team solution to ensure consistent styling between server-rendered and client-rendered components without introducing hydration mismatches?